//
//  EmoticonViewController.swift
//  Status
//
//  Created by Kylin on 16/3/27.
//  Copyright © 2016年 Kylin. All rights reserved.
//

import UIKit

private let emoticonCellID = "emoticonCellID"
class EmoticonViewController: UIViewController {

    // MARK:- 属性
    private lazy var packageManager : EmoticonManager = EmoticonManager()
    private var callBack : (emoticon : Emoticon) -> ()
    // MARK:- 懒加载属性
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonCollectionViewLayout())
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    // 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
      
    }
    
    // MARK:- 重写构造函数
    init(callBack : (emoticon : Emoticon) -> ()){
        self.callBack = callBack
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    

}

// MARK:- 设置UI介面
extension EmoticonViewController {
    /// 设置UI界面
    private func setupUI () {
        // 1:添加子控制器
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        // 2:设置frame
        collectionView.backgroundColor = UIColor(white: 0.94, alpha: 1.0)
        toolBar.backgroundColor = UIColor.lightGrayColor()
        
        // 使用系统自带方法来进行设置约束,需要先取消autoResizing
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        let views = ["toolBar" : toolBar,"collectionView" : collectionView]
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolBar(44)]-0-|", options:[.AlignAllLeft,.AlignAllRight], metrics: nil, views: views)
        
        view.addConstraints(cons)
        
        // 3.准备collectionView
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: emoticonCellID)
        
        // 添加toolBar
        setupToolBar()
        
    }
    
    private func setupToolBar () {
        // 1.定义titles的数组
        let titles = ["最近", "默认", "Emoji", "浪小花"]
        // 2.添加item
        var items = [UIBarButtonItem]()
        for i in 0..<titles.count {
            // 2.1.创建item
            let item = UIBarButtonItem(title: titles[i], style: .Plain, target: self, action: #selector(EmoticonViewController.itemClick(_:)))
            // 2.2.设置文字颜色
            item.tintColor = UIColor.orangeColor()
            
            // 2.3.设置item的tag
            item.tag = i
            // 2.4.将item添加到toolbar
            items.append(item)
            // 2.5.添加弹簧 生成间距
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
           
        }
        // 3:赋值
        items.removeLast() // 删除最后一个弹长肉
        toolBar.items = items
    }
    @objc private func itemClick (item : UIBarButtonItem) {
        // 1.获取点击的indexPath所在的组
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
        // 2.滚动到对应的位置
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
}
// MARK:- collectionView的数据源
extension EmoticonViewController : UICollectionViewDataSource{
    
    // 返顺总共有多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packageManager.packages.count
    }
    
    // 返回每一组有我少个Cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let package = packageManager.packages[section]
        return package.emoticons.count
    }
    
    // 设置cell的显示内容
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //1:创建cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emoticonCellID, forIndexPath: indexPath) as! EmoticonViewCell
        
        //2:给cell设置数据
       let package = packageManager.packages[indexPath.section]
        cell.emoticon = package.emoticons[indexPath.item]
        
        //3:返回cell
        return cell
    }
}

// MARK:- collectionView的代理方法
extension EmoticonViewController : UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 1.取出表情对象
        let package = packageManager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        // 2.插入最近表情
        inserRecentlyEmoticon(emoticon)
        
        // 3:将闭包回调给外面的控制器
        callBack(emoticon: emoticon)
    }
    
    /// 插入最近的表情
    func inserRecentlyEmoticon(emoticon:Emoticon){
        // 1.判断是否删除按钮和空白表情
        if emoticon.isRemove || emoticon.isEmpty {
            return
        }
        
        // 2.判断是否包含了emoticon表情
        if packageManager.packages[0].emoticons.contains(emoticon){
            let index = packageManager.packages[0].emoticons.indexOf(emoticon)!
            packageManager.packages[0].emoticons.removeAtIndex(index)
        }else{
            packageManager.packages[0].emoticons.removeAtIndex(19)
        }
        
        // 3.插入表情
        packageManager.packages[0].emoticons.insert(emoticon, atIndex: 0)
    }
}

// MARK:- 自定义布局Class
class EmoticonCollectionViewLayout : UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        // 1:定义常量
        let cols :CGFloat = 7
        let imageWH = UIScreen.mainScreen().bounds.width / cols
        
        // 2:设置布局
        itemSize = CGSize(width: imageWH, height: imageWH)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = .Horizontal // 滚动方向水平滚动
        
        // 3:设置cellView的属性
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        let insetMargin = (collectionView!.bounds.height - 3 * imageWH) / 2
        collectionView?.contentInset = UIEdgeInsets(top: insetMargin, left: 0, bottom: insetMargin, right: 0)
        
        
    }
}



